package com.dynomedia.esearch.util.groupkeycache;

import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dynomedia.esearch.util.groupkeycache.util.GkcConfig;

public class KeyBuffer {

	private static LinkedBlockingQueue<Key> bufferQueue = new LinkedBlockingQueue<Key>();
	
	private static final Log logger = LogFactory.getLog(KeyBuffer.class);
	
	static{
		KeyBufferConsumer.start();
		if(GkcConfig.getInstance().isMonitor()) Monitor.start();
		if(GkcConfig.getInstance().getDataDir().exists()) GroupkeyCache.start();
	}
	
	public static boolean add(String key){
		return add(GroupkeyCache.defaultGroupId,GroupkeyCache.defaultGroupname,key);
	}
	
	public static boolean add(Long id,String key){
		return add(id,GroupkeyCache.defaultGroupname,key);
	}
	
	/**
	 * 加入关键词缓冲
	 * baipeng wrote at 上午10:13:40 2009-10-21
	 * @param id
	 * @param group
	 * @param key
	 * @return
	 */
	public static boolean add(Long id,String group,String key){
		if(key != null) bufferQueue.add(new Key(id,group,key));
		return true;
	}
	
	public static Integer size(){
		if(logger.isDebugEnabled()) logger.debug("KeyBuffer status: bufferQueue.size = "+bufferQueue.size());
		return bufferQueue.size();
	}
	
	/**
	 * keyBufferConsumer一次获得所有缓冲数据
	 * baipeng wrote at 上午10:14:00 2009-10-21
	 * @return
	 */
	public static Collection<Key> drainTo(Collection<Key> bufferkeys) throws Exception{
		int buffersize = bufferQueue.size();		
		if(buffersize>0){
			bufferQueue.drainTo(bufferkeys);
			if(logger.isDebugEnabled()) logger.debug("KeyBuffer buffersize:"+buffersize+" drainTo size = "+bufferkeys.size()+" by Thread:"+Thread.currentThread().getName());
			return bufferkeys;
		}else{
			//block util bufferQueue add new Key Object;
			bufferkeys.add(bufferQueue.take());
		}
		return bufferkeys;
	}
	
	static class Key{
		
		private Long id;
		private String group;
		private String key;
		
		public Key(Long id,String group,String key){
			this.id = id;
			this.group = group;
			this.key = key;
		}
		
		public String toString(){
			return "[id]:"+id+" [group]:"+group+" [key]:"+key;
		}

		public Long getId() {
			return id;
		}
		public void setId(Long id) {
			this.id = id;
		}
		public String getGroup() {
			return group;
		}
		public void setGroup(String group) {
			this.group = group;
		}
		public String getKey() {
			return key;
		}
		public void setKey(String key) {
			this.key = key;
		}
	}
		
}
